package com.wish.g04.renting.controller;

import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.wish.g04.base.dto.SfContractDTO;
import com.wish.g04.base.entity.CwPaymentPlan;
import com.wish.g04.base.entity.MAttachment;
import com.wish.g04.base.entity.MOwner;
import com.wish.g04.base.entity.SfContract;
import com.wish.g04.base.service.ICwPaymentPlanService;
import com.wish.g04.base.service.IMOwnerService;
import com.wish.g04.base.service.ISfContractService;
import com.wish.g04.base.vo.SfContractVo;
import com.wish.g04.common.core.utils.StringUtils;
import com.wish.g04.common.core.utils.bean.BeanUtils;
import com.wish.g04.common.core.utils.poi.ExcelUtil;
import com.wish.g04.common.core.web.controller.BaseController;
import com.wish.g04.common.core.web.domain.AjaxResult;
import com.wish.g04.common.core.web.page.TableDataInfo;
import com.wish.g04.common.security.utils.SecurityUtils;
import com.wish.g04.renting.config.FileUtils;
import com.wish.g04.renting.service.PaymentPlanService;
import com.wish.g04.renting.service.TMAttachmentService;
import com.wish.g04.renting.service.TSfContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wish.g04.common.log.annotation.Log;
import com.wish.g04.common.log.enums.BusinessType;
import com.wish.g04.common.security.annotation.PreAuthorize;


/**
 * 【请填写功能名称】Controller
 * 
 * @author sangougou
 * @date 2022-05-27
 */
@RestController
@RequestMapping("/contract")
public class TSfContractController extends BaseController
{
    @Autowired
    private TSfContractService tSfContractService;
    @Autowired
    PaymentPlanService paymentPlanService;
    @Autowired
    IMOwnerService imOwnerService;
    @Autowired
    ISfContractService iSfContractService;
    @Autowired
    ICwPaymentPlanService iCwPaymentPlanService;
    @Autowired
    TMAttachmentService tmAttachmentService;

    /**
     * 查询【收房】列表
     */
    @PreAuthorize(hasPermi = "system:contract:list")
    @GetMapping("/list")
    public TableDataInfo list(SfContractDTO sfContractDTO)
    {
        startPage();
        TableDataInfo getlist = tSfContractService.getlist(sfContractDTO);
        return getlist;
    }


    /**
     * 新增【收房】
     */
    @PreAuthorize(hasPermi = "system:contract:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("addSfContract")
    public AjaxResult addSfContract(@RequestBody SfContract sfContract)
    {
        //如果上一合同编号为空则录入,如果不为空则为续约
        Long lastContractId = sfContract.getLastContractId();
        //若为续约合同则变更原合同为已续约
        if(lastContractId!=null){
            tSfContractService.updateXyStatus(sfContract.getLastContractId());
        }
        //使用hutool工具类IdUtil获取雪花算法
        Snowflake snowflake = IdUtil.getSnowflake();
        //雪花算法生成合同id，拼接前缀“SFHT”
        sfContract.setSfContractNo("SFHT" + snowflake.nextId());
        //是否为签约人，默认是，0是1否
        Boolean signWithOwner = sfContract.getSignWithOwner();
        //新建业主
        MOwner tmOwner = new MOwner();
        //将收房合同相同字段赋值
        BeanUtils.copyBeanProp(tmOwner, sfContract);


//        if(StringUtils.isNotEmpty(tmOwner.getIdCard()))
//            sfContract.setOwnerIdCard(tmOwner.getIdCard());
//        if(StringUtils.isNotEmpty(tmOwner.getMobile()))
//            sfContract.setOwnerMobile(tmOwner.getMobile());
//        if(StringUtils.isNotEmpty(tmOwner.getAddress()))
//            sfContract.setOwnerContactAddress(tmOwner.getAddress());
//        if(StringUtils.isNotEmpty(tmOwner.getUrgMobile()))
//            sfContract.setSignUserEmergencyPhone(tmOwner.getUrgMobile());

        //是签约人就给签约人字段赋值(写死了我)
        if (signWithOwner) {
            sfContract.setSignUserName(sfContract.getOwnerName());
            sfContract.setSignUserIdCard(sfContract.getOwnerIdCard());
            sfContract.setSignUserMobile(sfContract.getOwnerMobile());
        }
        //获取用户id
        Long userId = SecurityUtils.getUserId();
        tmOwner.setCreateUserid(userId);
        tmOwner.setCreateTime(new Date());
        tmOwner.setUpdateUserid(userId);
        tmOwner.setUpdateTime(new Date());
        //录入合同添加业主
        if(lastContractId==null){
            imOwnerService.save(tmOwner);
            //将业主的id存入合同中
            sfContract.setOwnerId(tmOwner.getId());
        }
        //签订时间
        sfContract.setConSignTime(new Date());
        //录入时间
        sfContract.setConInfoTime(new Date());
        //审核时间
        sfContract.setConAudTime(new Date());
        //创建时间
        sfContract.setCreateTime(new Date());
        //修改时间
        sfContract.setUpdateTime(new Date());
        //创建用户id
        sfContract.setCreateUserid(userId);
        //修改用户id
        sfContract.setUpdateUserid(userId);
        //合同录入人
        sfContract.setOperId(userId);
        //收房人
        sfContract.setSfUserId(userId);
        //获取用户名
        String username = SecurityUtils.getUsername();
        //签约人（甲方）
        sfContract.setSignUserName(username);
        //收房人
        sfContract.setSfUserName(username);
        //已提交
        sfContract.setStatus(2);
        //保存合同录入
        iSfContractService.save(sfContract);
        //获取新增合同id
        Long contractVOId = sfContract.getId();
        String sfContractNo = sfContract.getSfContractNo();

        List<MAttachment> attachmentList = sfContract.getAttachmentList();
        if(attachmentList!=null){
            //增加附件（支持多文件上传）
            tmAttachmentService.saveAttachments(sfContract);
        }

        //保存付款单t_cw_payment_plan
        //获取账单
        List<CwPaymentPlan> paymentPlans = paymentPlanService.getPaymentPlans(sfContract);
        //赋值账单中的信息
        for (CwPaymentPlan paymentPlan : paymentPlans) {
            //付款单号
            paymentPlan.setPayOrderNo("SFHT" + snowflake.nextId());
            paymentPlan.setContractId(contractVOId);
            paymentPlan.setContractNo(sfContractNo);
            paymentPlan.setCreateTime(new Date());
            paymentPlan.setUpdateTime(new Date());
            paymentPlan.setCreateUserid(userId);
            paymentPlan.setUpdateUserid(userId);
            paymentPlan.setOwnerName(sfContract.getOwnerName());
            paymentPlan.setBusinessId(sfContract.getBusinessId());
        }
        boolean b = iCwPaymentPlanService.saveBatch(paymentPlans);
        System.err.println(paymentPlans);
        //创建电子合同
//        return createEDocument(sfContract);
        return AjaxResult.success();
    }

    @GetMapping("createEDocument")
    public AjaxResult createEDocument(SfContract sfContract){
        String templatePath = "C:/Users/123/Desktop/ht-template.docx";    //固定模板路径
        String fileDir = "C:/Users/123/Desktop/";  //生成文档路径
        String s = UUID.randomUUID().toString();
        String fileName = System.currentTimeMillis()+"";   //文件名
        Map<String,Object> params = new HashMap<>();
        params. put("signUserName", sfContract.getSignUserName());
        params.put("premiseName",sfContract.getPremiseName());
        params.put("houseName",sfContract.getHouseName());
        params.put("leaseStartTime",sfContract.getLeaseStartTime().toString());
        params.put("leaseEndTime",sfContract.getLeaseEndTime().toString());
        String wordPath = FileUtils.createWord(templatePath, fileDir, fileName, params);
        System.out.println("生成文档的名字 = " + wordPath);
        return AjaxResult.success("成功666",wordPath);
    }

    @PostMapping("/getPaymentPlanList")
    public AjaxResult getPaymentPlanList(@RequestBody SfContract sfContract ) {
        System.err.println(sfContract);
        return AjaxResult.success(paymentPlanService.getPaymentPlans(sfContract));
    }

//    /**
//     * 导出【请填写功能名称】列表
//     */
//    @PreAuthorize(hasPermi = "system:contract:export")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, SfContract sfContract) throws IOException
//    {
//        List<SfContract> list = tSfContractService.selectTSfContractList(tSfContract);
//        ExcelUtil<SfContract> util = new ExcelUtil<SfContract>(SfContract.class);
//        util.exportExcel(response, list, "contract");
//    }

//    /**
//     * 获取【请填写功能名称】详细信息
//     */
//    @PreAuthorize(hasPermi = "system:contract:query")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id)
//    {
//        return AjaxResult.success(tSfContractService.selectTSfContractById(id));
//    }
//

//
//    /**
//     * 修改【请填写功能名称】
//     */
//    @PreAuthorize(hasPermi = "system:contract:edit")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody TSfContract tSfContract)
//    {
//        return toAjax(tSfContractService.updateTSfContract(tSfContract));
//    }
//
//    /**
//     * 删除【请填写功能名称】
//     */
//    @PreAuthorize(hasPermi = "system:contract:remove")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids)
//    {
//        return toAjax(tSfContractService.deleteTSfContractByIds(ids));
//    }
}
